package com.zhengxing.jienci.redis.aspectj;

import com.zhengxing.jienci.redis.annotation.DelCache;
import com.zhengxing.jienci.redis.util.KeyUtils;
import com.zhengxing.jienci.redis.util.RedisUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;

/**
 * @author 浪遏飞舟
 * @create 2020-06-22 11:35
 * 删除缓存切面类
 */
@Configuration
@Aspect
@Order(2)
public class DelCacheAspect {

    @Autowired
    private RedisUtils redisUtils;

    @Pointcut("@annotation(com.zhengxing.jienci.redis.annotation.DelCache)")
    public void pointcut(){}



    /**
     * 方法后置增强
     * @param point
     * @return
     */
    @AfterReturning(value = "pointcut()")
    public void after(JoinPoint point){
        try {
            //获得DelCache注解的属性值
            MethodSignature signature = (MethodSignature) point.getSignature();
            Method method = signature.getMethod();
            DelCache annotation = method.getAnnotation(DelCache.class);
            //获得key
            String key = KeyUtils.getCacheKey(annotation, point);
            //删除缓存
            redisUtils.delCache(key);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
